<?php

namespace App\Http\Controllers;

use App\Models\Coin;
use App\Models\CoinClue;
use App\Models\CoinClueGlobal;
use App\Models\UserCoin;
use App\Models\UserCoinClue;
use App\Models\AdminSetting;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CoinController extends Controller
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function list(Request $request)
    {
        $type = $request->input('type', '');
        $list = Coin::query()->where('status', Coin::STATUS_OPEN)
            ->where(function ($query) use ($type) {
                if ($type) {
                    $query->whereIn('type', explode(',', $type));
                } else {
                    $query->where('type', '!=', Coin::TYPE_JIN)->where('type', '!=', Coin::TYPE_ZM);
                }
            })->get();
        $userCoin = UserCoin::query()
            ->where('user_id', $request->user()->id)
            ->whereIn('coin_id', $list->pluck('id')->toArray())
            ->get()->keyBy('coin_id');
        $coinClue = CoinClue::query()->where('is_circle', CoinClue::IS_CIRCLE_YES)->whereIn('coin_id', $list->pluck('id')->toArray())->get()->groupBy('coin_id');
        $coinClueIds = CoinClue::query()->where('is_circle', CoinClue::IS_CIRCLE_YES)->whereIn('coin_id', $list->pluck('id')->toArray())->get()->pluck('id')->toArray();
        $userCoinClue = UserCoinClue::query()->where('user_id', $request->user()->id)->where(function ($query) use ($coinClueIds) {
            if ($coinClueIds) {
                $query->whereIn('coin_clue_id', $coinClueIds);
            } else {
                $query->whereRaw('1 != 1');
            }
        })->where('status', UserCoinClue::STATUS_DONE)->orderBy('created_at', 'desc')->get()->groupBy('coin_id');

        $isFalse = false; // 金币列表，标识是否存在假金币
        foreach ($list as $key => &$value) {
            if ($value->type != Coin::TYPE_JIN) {
                if (!$value->false_latitude || !$value->false_longitude) {
                    $initialRadius = $value->type == Coin::TYPE_YIN ? self::RADIUS_SILVER : self::RADIUS_COPPER;
                    $initialCenter = $this->generateRandomPointInCircle($value->latitude, $value->longitude, $initialRadius);
                    $value->false_latitude = $initialCenter['lat'];
                    $value->false_longitude = $initialCenter['lng'];
                    $value->save();
                } // 老版本兼容，给没有假经纬度数据的硬币初始化

                if ($value->is_unlock === 1) { // 已解锁
                    $value->radius = 0;
                } else { // 未被解锁
                    $clue_count = isset($coinClue[$value->id]) ? $coinClue[$value->id]->count() : 0;
                    $user_clue_count = 0;
                    if (isset($userCoinClue[$value->id])) {
                        $user_clue_count = $userCoinClue[$value->id]->count();
                        $value->false_latitude = $userCoinClue[$value->id][0]->latitude;
                        $value->false_longitude = $userCoinClue[$value->id][0]->longitude;
                        $value->radius = $userCoinClue[$value->id][0]->radius;
                    } else {
                        $value->radius = $value->type == Coin::TYPE_YIN ? self::RADIUS_SILVER : self::RADIUS_COPPER;
                    }
                    $value->latitude = $value->false_latitude;
                    $value->longitude = $value->false_longitude;
                    $user_clue_count = min($user_clue_count, $clue_count);
                    if ($user_clue_count === $clue_count) {
                        $value->radius = 0;
                    }
                }
            } else {
                if (isset($userCoin[$value->id]) && $value->is_true === Coin::IS_TRUE_NO) {
                    unset($list[$key]);
                } else {
                    if ($value->is_true === 0) {
                        $isFalse = true;
                    }
                    if ($value->is_unlock === Coin::IS_UNLOCK_YES) {
                        $value->radius = 0;
                    } else {
                        // 计算正六边形
                        $value->polygon = [
                            'points' => $this->generateHexagon($value->latitude, $value->longitude, 500),
                            'strokeWidth' => 2,
                            'strokeColor' => '#FFFFFF',
                            'fillColor' => '#FFC46DA3'
                        ];
                        $value->radius = 500;
                    }
                }
            }
            unset($value->false_latitude);
            unset($value->false_longitude);
            unset($value->created_at);
            unset($value->deleted_at);
            unset($value->status);
            unset($value->is_true);
            unset($value->updated_at);
            unset($value->amount);
        }
        unset($value);
        $returnData = $list->values()->toArray();
        if ($type == Coin::TYPE_JIN) {
            $returnData = [
                'list' => $returnData,
                'is_false' => $isFalse
            ];
        }
        return $this->success($returnData);
    }

    public function info(Request $request)
    {
        $id = $request->input('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $coin = Coin::query()->find($id);
        if (!$coin) {
            return $this->error('硬币不存在');
        }

        return $this->success($coin->toArray());
    }

    public function clueList(Request $request)
    {
        $id = $request->input('id');
        $userId = $request->user()->id;
        if (!$id) {
            return $this->error('参数错误');
        }
        $coin = Coin::query()->find($id);
        if (!$coin) {
            return $this->error('硬币不存在');
        }
        if ($coin->type == Coin::TYPE_JIN) {
            $global = CoinClueGlobal::query()->orderBy('updated_at', 'desc')->get()->each(function ($item) {
                $item['is_unlock'] = CoinClue::IS_UNLOCK_YES;
                return $item;
            });
            $goldPrice = AdminSetting::query()->where('slug', '金币解锁价格')->first();
            $price = '500'; // 默认500橡果
            if ($goldPrice) {
                $price = $goldPrice['value'];
            }
            return $this->success(['list' => $global, 'price' => intval($price)]);
        }

        $clue = CoinClue::query()->where('coin_id', $id)->get()->toArray();
        $userCoinClue = UserCoinClue::query()->where(['coin_id' => $id, 'user_id' => $userId])->get()->keyBy('coin_clue_id')->toArray();

        foreach ($clue as &$value) {
            if ($value['number']) {
                $value['is_unlock'] = isset($userCoinClue[$value['id']]) && $userCoinClue[$value['id']]['number'] >= $value['number'] ? CoinClue::IS_UNLOCK_YES : CoinClue::IS_UNLOCK_NO;
                $value['is_unlock_number'] = $userCoinClue[$value['id']]['number'] ?? 0;
            } else {
                $value['is_unlock'] = isset($userCoinClue[$value['id']]) ? CoinClue::IS_UNLOCK_YES : CoinClue::IS_UNLOCK_NO;
            }
        }
        unset($value);
        return $this->success($clue);
    }

    public function userTop(Request $request)
    {
        $list = UserCoin::query()
            ->leftJoin('coin', 'coin.id', '=', 'user_coin.coin_id')
            ->leftJoin('users', 'user_coin.user_id', '=', 'users.id')
            ->selectRaw('user_coin.user_id, count(*) as num, coin.type, users.name')
            ->groupBy(['coin.type', 'user_coin.user_id'])
            ->orderBy('coin.type', 'asc')
            ->orderBy('num', 'desc')
            ->get()->groupBy('type')->toArray();


        return $this->success($list);
    }

    /**
     * 前端找到硬币，扫码后获取的信息
     * @param id 硬币id
     * @param token 用于校验用户扫码合法性
     */
    public function getCoinInfo(Request $request)
    {
        $id = $request->input('id');
        $token = $request->input('token');

        if (!$id || !$token) return $this->error('参数错误');

        $coin = Coin::select('id', 'name', 'type', 'longitude', 'latitude', 'address', 'is_unlock', 'icon', 'is_new_user_only')->where('id', $id)->first();
        if ($coin['is_unlock'] === Coin::IS_UNLOCK_YES) {
            return $this->error('该硬币已被领取');
        }
        unset($coin['is_unlock']);
        $returnData = clone $coin;
        unset($coin['name']);
        unset($coin['address']);
        unset($coin['icon']);
        unset($coin['is_new_user_only']);
        $token = md5(json_encode($coin));
        if ($token !== $request->input('token')) {
            return $this->error('token错误');
        }
        return $this->success($returnData); // 验证通过，返回此硬币信息
    }

    /**
     * 查看硬币的找到证据 视频
     */
    public function getCoinVideo(Request $request)
    {
        $coin_id = $request->input('coin_id');
        // $userId = $request->user();
        $coin = UserCoin::query()->where('coin_id', $coin_id)->first();
        if (!$coin) return $this->error('数据混乱，未找到硬币被领取的信息');
        return $this->success($coin->content);
    }
}
